package sz.szsmk.citizencard.ui.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.DefaultLayoutHelper;
import com.chenenyu.router.annotation.Route;
import com.google.gson.Gson;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.RoutineActivityBinding;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.response.CardInfo;
import sz.szsmk.citizencard.model.network.bean.response.QueryUserCardResponse;
import sz.szsmk.citizencard.mvp.contract.IRoutineCardContact;
import sz.szsmk.citizencard.mvp.presenter.RoutineCardPresenter;
import sz.szsmk.citizencard.ui.adapter.CardViewFunAdapter;
import sz.szsmk.citizencard.ui.adapter.RoutineHeadAdapter;
import sz.szsmk.citizencard.ui.adapter.RoutineOneAdapter;
import sz.szsmk.citizencard.ui.adapter.RoutineTwoAdapter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PubUtils;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/7/16 15:03
 * description:
 */
@Route("carddetail")
public class HomeRoutineCardActivity extends IBaseActivity<RoutineCardPresenter, RoutineActivityBinding>
        implements IRoutineCardContact.IRoutineCardView, View.OnClickListener {

    private RecyclerView rotineRv;
    private List<DelegateAdapter.Adapter> adapters;
    private ArrayList<QueryUserCardResponse.DataBean> cardInfo;
    private ArrayList<CardInfo> cardInfoList;
    private ArrayList<CardInfo> list;
    private List<View> viewList;
    private View view;
    private int mPosition;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<ArrayList<QueryUserCardResponse.DataBean>> mendList;
    private ViewPager cardInfoVp;
    public RoutineOneAdapter oneAdapter;
    public RoutineTwoAdapter routineTwoAdapter;
    public RoutineHeadAdapter routineHeadAdapter;
    private Button delBtn;
    private ArrayList<String> openList;
    private String type;


    @Override
    protected int attachLayoutRes() {
        return R.layout.routine_activity;
    }

    @Override
    protected void initInjector() {

        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        rotineRv = dataBinding.rotineRv;
        type = getIntent().getStringExtra("type");
        initLayout();

        viewList = new ArrayList<View>();
        TextView bjTv = dataBinding.titleLayout.bjTv;
        dataBinding.titleLayout.settingTitle.setText("市民卡");
        dataBinding.titleLayout.settingTitle.setTextColor(this.getResources().getColor(R.color.white));
        bjTv.setVisibility(View.VISIBLE);
        bjTv.setText("交易记录");
        bjTv.setTextColor(this.getResources().getColor(R.color.white));
        bjTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mendList!=null){
                    ArrayList<QueryUserCardResponse.DataBean> dataBeans = mendList.get(mPosition);
                    String cardNo = dataBeans.get(0).getCardNo();
                    Bundle bundle = new Bundle();
                    bundle.putString("cardNo",cardNo);
                    JumpUtils.jumptoNatvie(HomeRoutineCardActivity.this, "trans", 0,bundle);
                }
            }
        });
        dataBinding.titleLayout.bjTv.setTextColor(this.getResources().getColor(R.color.white));
        dataBinding.titleLayout.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Intent intent = getIntent();
        if ("action".equals(intent.getAction())) {
            list = (ArrayList<CardInfo>) intent.getSerializableExtra("cardInfoList");
            L.e(Constant.TAG, "list==============" + list.size());
            for (int i = 0; i < list.size(); i++) {
                L.e(Constant.TAG, "CardInfo=========" + list.get(i).getCardNickName());
            }
        }

        delBtn = (Button) findViewById(R.id.card_delcard);
        delBtn.setOnClickListener(this);
    }

    private void initLayout() {
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return true;
            }
        };

        rotineRv.setLayoutManager(layoutManager);
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        rotineRv.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 30);
        DelegateAdapter delegateAdapter = new DelegateAdapter(layoutManager, true);
        rotineRv.setAdapter(delegateAdapter);
        adapters = new LinkedList<>();

        //头部适配器
        DefaultLayoutHelper headHelper = new DefaultLayoutHelper();
        routineHeadAdapter = new RoutineHeadAdapter(this, headHelper);
        adapters.add(routineHeadAdapter);

        //惠民、园林、亲子适配器
        DefaultLayoutHelper oneHelper = new DefaultLayoutHelper();
        oneAdapter = new RoutineOneAdapter(this, oneHelper);
        adapters.add(oneAdapter);

        //文化消费 体育惠民
        DefaultLayoutHelper twoHelper = new DefaultLayoutHelper();
        routineTwoAdapter = new RoutineTwoAdapter(this, twoHelper);
        adapters.add(routineTwoAdapter);


        delegateAdapter.setAdapters(adapters);
    }

    @Override
    protected void updateViews() {
        mPresenter.queryUserCard(type, type);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.card_delcard) {
            PubUtils.popTipOrWarn(this, "删除的卡片" + mPosition);
        } else {
            throw new IllegalStateException("Unexpected value: " + v.getId());
        }
    }


    public static List<String> removeDuplicate(ArrayList<String> titles) {
        Set set = new LinkedHashSet<String>();
        set.addAll(titles);
        titles.clear();
        titles.addAll(set);
        return titles;
    }

    @Override
    public void queryUserCardSuccess(QueryUserCardResponse response) {

        List<QueryUserCardResponse.DataBean> data = response.getData();
        if (data != null) {
            routineHeadAdapter.setViewData(data);
            routineHeadAdapter.notifyDataSetChanged();
        }
        if (data != null) {
            ArrayList<String> titles = new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                titles.add(data.get(i).getCardNo());
            }
            List<String> newList = removeDuplicate(titles);

            mendList = new ArrayList<>();

            for (int i = 0; i < newList.size(); i++) {
                String cardNo = newList.get(i);

                //卡片详情集合
                cardInfo = new ArrayList<>();
                mendList.add(cardInfo);

                for (int j = 0; j < data.size(); j++) {
                    QueryUserCardResponse.DataBean dataBean = data.get(j);
                    String cardNo1 = dataBean.getCardNo();
                    if (cardNo.equals(cardNo1)) {
                        cardInfo.add(dataBean);
                    }

                }
            }
            L.e(Constant.TAG, "mendList===============" + mendList.size());
            L.e(Constant.TAG, "cardInfo===============" + cardInfo.size());
        }
        cardInfoVp = dataBinding.cardInfoVp;
        for (int i = 0; i < mendList.size(); i++) {
            view = LayoutInflater.from(this).inflate(R.layout.card_view, null, false);
            viewList.add(view);
            final int finalI = i;
        }

        MyPagerAdapter vpAdapter = new MyPagerAdapter(viewList);

        cardInfoVp.setAdapter(vpAdapter);
        cardInfoVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                mPosition = position;


            }

            @Override
            public void onPageSelected(int position) {
                mPosition = position;
                setView(position);
//                L.e(Constant.TAG, "onPageScrolled==========2" + position);
//                Toast.makeText(HomeRoutineCardActivity.this, position+"", Toast.LENGTH_SHORT).show();
//                mPosition = position;
//                ArrayList<QueryUserCardResponse.DataBean> dataBeen = mendList.get(position);
//                if (dataBeen.get(0).getFuncCode().equals("09")) {
//                    //省卡
//                    QueryUserCardResponse.DataBean sCard = dataBeen.get(0);
//                } else {
//                    QueryUserCardResponse.DataBean huiminData = dataBeen.get(0);
//                    QueryUserCardResponse.DataBean ylBean = dataBeen.get(1);
//                    QueryUserCardResponse.DataBean qzBean = dataBeen.get(2);
//                    QueryUserCardResponse.DataBean whBean = dataBeen.get(3);
//                    QueryUserCardResponse.DataBean tyhmBean = dataBeen.get(4);
//
//                    routineTwoAdapter.setTyhmData(tyhmBean);
//                    routineTwoAdapter.setWhxfData(whBean);
//                    oneAdapter.setYldata(ylBean);
//                    oneAdapter.setHuiminData(huiminData);
//                    oneAdapter.setQzwwkData(qzBean);
//                    oneAdapter.notifyDataSetChanged();
//                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        cardInfoVp.setCurrentItem(0);

    }

    private void setView(int position) {
        ArrayList<QueryUserCardResponse.DataBean> dataBeen = mendList.get(position);
        if (dataBeen.get(0).getFuncCode().equals("09")) {
            //省卡
            QueryUserCardResponse.DataBean sCard = dataBeen.get(0);
        } else {
            QueryUserCardResponse.DataBean huiminData = dataBeen.get(0);
            QueryUserCardResponse.DataBean ylBean = dataBeen.get(1);
            QueryUserCardResponse.DataBean qzBean = dataBeen.get(2);
            QueryUserCardResponse.DataBean whBean = dataBeen.get(3);
            QueryUserCardResponse.DataBean tyhmBean = dataBeen.get(4);

            routineTwoAdapter.setTyhmData(tyhmBean);
            routineTwoAdapter.setWhxfData(whBean);
            oneAdapter.setYldata(ylBean);
            oneAdapter.setHuiminData(huiminData);
            oneAdapter.setQzwwkData(qzBean);
            oneAdapter.notifyDataSetChanged();
        }
    }

    private class MyPagerAdapter extends PagerAdapter {
        private List<View> mViewList;
        private TextView homeCardName;
        private TextView homeCardBalance;
        private TextView homeCardId;
        private TextView cardSize;
        private LinearLayout homeBind;
        private ArrayList<CardInfo> cardInfoList;
        private RecyclerView cardViewRv;

        MyPagerAdapter(List<View> viewList) {
            mViewList = viewList;
        }

        @Override
        public int getCount() {
            return null == mViewList ? 0 : mViewList.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }


        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View view = mViewList.get(position);

            L.e(Constant.TAG, "mViewList----------" + mViewList.size());
            //单张卡片数据been
            ArrayList<QueryUserCardResponse.DataBean> been = (ArrayList<QueryUserCardResponse.DataBean>) mendList.get(position);
            cardInfoList = new ArrayList<>();
            openList = new ArrayList<>();
            for (int i = 0; i < been.size(); i++) {
                String stateName = been.get(i).getStateName();
                if (stateName!=null){
                    if (stateName.equals("已开通")){
                        //获取已开通的功能卡名称
                        String funcName = been.get(i).getFuncName();
                        openList.add(funcName);
                    }
                }
            }

            L.e(Constant.TAG, "been=========" + been.size());
            if (been != null) {
                for (int i = 0; i < been.size(); i++) {
                    QueryUserCardResponse.DataBean dataBean = been.get(i);
                    String json = new Gson().toJson(dataBean);
                    CardInfo info = new Gson().fromJson(json, CardInfo.class);
                    cardInfoList.add(info);
                }
                homeCardName = (TextView) view.findViewById(R.id.home_card_name);
                homeCardBalance = (TextView) view.findViewById(R.id.home_card_balance);
                homeCardId = (TextView) view.findViewById(R.id.home_card_id);
                cardSize = (TextView) view.findViewById(R.id.home_card_size);
                if (mViewList!=null){
                    cardSize.setText("已绑定" + mViewList.size() + "张");
                }
                cardViewRv = (RecyclerView) view.findViewById(R.id.card_view_rv);
                GridLayoutManager manager = new GridLayoutManager(HomeRoutineCardActivity.this, 6);
                cardViewRv.setLayoutManager(manager);
                CardViewFunAdapter funAdapter = new CardViewFunAdapter(HomeRoutineCardActivity.this, openList);
                cardViewRv.setAdapter(funAdapter);
                homeBind = (LinearLayout) view.findViewById(R.id.home_bind);

                homeBind.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("key", "home");
                        JumpUtils.jumptoNatvie(HomeRoutineCardActivity.this, "addnewcard", 0, bundle);
                    }
                });
                setView(position);
                ArrayList<QueryUserCardResponse.DataBean> dataBeen = mendList.get(position);
                QueryUserCardResponse.DataBean dataBean = dataBeen.get(0);
//                setView(0);
                homeCardId.setText(dataBean.getCardNo());
                double balance = (double) dataBean.getCardBalance();

                double mBalance = balance / 100;
                String string = doubleToString(mBalance);
                homeCardBalance.setText(string);
                homeCardName.setText(dataBean.getCardNickName());

                container.addView(view);
            }


            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));
        }
    }

    @Override
    public void queryUserCardFalie(String msg) {

    }

    @Override
    public void unBindCardFail(String message) {

    }

    @Override
    public void unBindCardSucc() {

    }

    @Override
    public void modifyCardNickNameSucc() {

    }

    @Override
    public void modifyCardNickNameFail() {

    }

    @Override
    public void queryUserCardInfoTempSucc() {

    }

    @Override
    public void queryUserCardInfoTempFail() {

    }

    public static String doubleToString(double num) {
        //使用0.00不足位补0，#.##仅保留有效位
        return new DecimalFormat("0.00").format(num);
    }

    public static String changeF2Y(int price) {
        return BigDecimal.valueOf(Long.valueOf(price)).divide(new BigDecimal(100)).toString();
    }
}
